import assert from 'assert-plus'
import _ from 'lodash'
import config from '../../config.json'
import ptimeApi from './ptime'
import os from 'os'

// oauth验权限
const oauth = ({clientId, redirectUri, responseType, scope, state}) => {
	assert.string(clientId);
	assert.string(redirectUri);
	assert.string(responseType);

	return async (ctx, next) => {

		const info = _.assign({}, ctx.session, ctx.request.query, ctx.request.body);
		if (info && info.token) {
			ctx.state.user = await ptimeApi.getUserWithToken(info.token);
			if (!ctx.state.user) {
				ctx.redirect(`${config.oauth.url}?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=${responseType}&state=1`);
			} else {
				ctx.session.token = info.token
			}
		}

		const query = ctx.request.query;
		if (query.token) {
			ctx.redirect(ctx.request.path);
		}
		await next();

	}
}

const oauthPathGen = (redirectUri, responseType) => {
	return `${config.oauth.url}?client_id=${config.oauth.clientId}&redirect_uri=${encodeURIComponent(`${config.oauth.redirectBase}${redirectUri}`)}&response_type=${responseType}&state=1`
}

export {oauth, oauthPathGen};